<template>
  <el-card shadow="never">
    <div slot="header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }"> <i class="el-icon-house"></i> 首页</el-breadcrumb-item>
        <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 内容区域 -->
    <div class="filter-form">
      <div class="ipt"></div>
      <el-button type="primary"
                 size="small"
                 icon="el-icon-plus">增加</el-button>
    </div>
    <!-- 表格 -->
    <el-table :data="list"
              border>
      <!-- 折叠列 -->
      <el-table-column type="expand"
                       label="#">
        <template slot-scope="scope">
          <template v-if="scope.row.children.length">
            <!-- 去渲染该角色的所有权限 -->
            <el-row class="line"
                    v-for="item in scope.row.children"
                    :key="item.id">
              <el-col :span="4">
                <el-tag type="primary">{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="20">
                <el-row class="line"
                        v-for="val in item.children"
                        :key="val.id">
                  <el-col :span="4">
                    <el-tag type="success">{{val.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="20">
                    <el-tag type="warning"
                            closable
                            @close="delTag(v,scope.row)"
                            v-for="v in val.children"
                            :key="v.id">{{v.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
          <template v-else>
            <p>角色没有关联权限，暂无数据信息</p>
          </template>
        </template>
      </el-table-column>

      <!-- 正常列 -->
      <el-table-column type="index"
                       width="120"
                       label="序号"></el-table-column>
      <el-table-column prop="roleName"
                       label="角色名称"></el-table-column>
      <el-table-column prop="roleDesc"
                       label="角色描述"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="success"
                     size="small"
                     circle
                     icon="el-icon-edit"></el-button>
          <el-button type="danger"
                     size="small"
                     circle
                     icon="el-icon-delete"></el-button>
          <el-button @click="openAuth(scope.row)"
                     type="warning"
                     size="small"
                     circle
                     icon="el-icon-setting"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 角色授权权限 -->
    <el-dialog title="角色授权"
               :visible.sync="isAuthShow"
               width="30%"
               @close="defCheck=[]">
      <!-- 树形控件 -->
      <el-tree :data="treeList"
               ref="tree"
               v-if="isAuthShow"
               node-key="id"
               show-checkbox
               default-expand-all
               :default-checked-keys="defCheck"
               :props="{ label:'authName',children:'children' }"></el-tree>
      <span slot="footer">
        <el-button @click="isAuthShow = false">取消</el-button>
        <el-button type="primary"
                   @click="authSubmit">确定</el-button>
      </span>
    </el-dialog>

  </el-card>
</template>

<script>
export default {
  name:'Roles',
  data () {
    return {
      list: [],
      treeList:[], // 树的数据（树形权限数据）
      isAuthShow:false,
      defCheck:[], // 修改角色的权限信息
      changeRoleId:''
    }
  },
  created () {
    this.getRolesList()
    this.getRightsList()
  },
  methods: {
    // 获取权限列表
    async getRightsList () {
      const { data:res } = await this.$axios.get('/rights/tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.treeList = res.data
    },
    // 获取角色列表
    async getRolesList () {
      const { data:res } = await this.$axios.get('/roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.list = res.data
    },
    // 删除角色的指定权限
    async delTag (val, row) {
      try {
        await this.$confirm('确定删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        // val是点击标签的数据，row是这大一行的数据
        const { data:res } = await this.$axios.delete(`/roles/${row.id}/rights/${val.id}`)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        row.children = res.data // res.data 是当前角色的所有权限信息
        this.$message.success(res.meta.msg)
      } catch (error) {
        console.log(error)
        this.$message.info('取消删除')
      }
    },
    // 授权按钮
    openAuth (row) {
      // 只要取出树形数据里面每个最底层的id给defCheck
      this.getLeafKeys(row, this.defCheck)
      // 设置角色ID
      this.changeRoleId = row.id
      // 弹框打开
      this.isAuthShow = true
    },
    // 递归方法
    getLeafKeys (node, arr) {
      // 该函数会获取到当前角色的所有三级权限id并添加到defKeys中
      // 如果当前节点不包含children属性，则表示node为三级权限
      if (!node.children) {
        return arr.push(node.id)
      }
      // 递归调用
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 角色关联权限
    async authSubmit () {
      // 选中getCheckedKeys
      // 半选getHalfCheckedKeys
      let rids = [...this.$refs.tree.getCheckedKeys(), ...this.$refs.tree.getHalfCheckedKeys()]
      // 将数组变成字符串
      rids = rids.join(',')
      // 发请求
      const { data:res } = await this.$axios.post('/roles/' + this.changeRoleId + '/rights', {
        rids
      })
      // 错误处理
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 成功处理   提示框、修改角色ID重置、关闭弹框、拉取列表
      this.$message.success(res.meta.msg)
      this.changeRoleId = ''
      this.isAuthShow = false
      this.getRolesList()
    }
  }
}
</script>

<style scoped>
.line{
  border-bottom: 1px solid #ddd;
  padding: 10px;
  align-items: center;
  display: flex;

}
.line:last-child{
  border:none;
  padding-bottom: 0;
}
.el-tag{
  margin:5px;
}
</style>
